package com.haiyu.manager.controller.platform;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;

import com.haiyu.manager.dto.Category1DTO;
import com.haiyu.manager.pojo.Category1;
import com.haiyu.manager.response.PageDataResult;
import com.haiyu.manager.service.Category1Service;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.slf4j.Logger;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("category1")//指定路由
public class Category1Controller {
    @Autowired
    private Category1Service category1Service;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${uploadFile.resourceHandler}")
    private String resourceHandler;//请求 url 中的资源映射，，如 /uploadFiles/**

    @Value("${uploadFile.location}")
    private String uploadFileLocation;//上传文件保存的本地目录，使用@Value获取全局配置文件中配置的属性值，如 E:/wmx/uploadFiles/

    @Value("${uploadFile.h-upload}")
    private String uploadFileHupload;
    @Value("${uploadFile.w-upload}")
    private String uploadFileWupload;



    @ResponseBody
    @RequestMapping(value = "/uploadImage", method = {RequestMethod.POST})
    public Map<String, Object> uploadImage(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "file", required = false) MultipartFile file) throws IOException{

        Map<String, Object> result = new HashMap<>();
        String path = null;
        //////图片访问路径
        String fileServerPath;

        System.out.println("执行upload");
        request.setCharacterEncoding("UTF-8");
        logger.info("执行图片上传");
        if(!file.isEmpty()) {
            logger.info("成功获取照片");
            String fileName = file.getOriginalFilename();
            //String path = null;
            String type = null;
            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            logger.info("图片初始名称为：" + fileName + " 类型为：" + type);
            if (type != null) {
                if ("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())||"JPEG".equals(type.toUpperCase())) {
                    // 项目在容器中实际发布运行的根路径
                    //String realPath = request.getSession().getServletContext().getRealPath("/");
                    String realPath=uploadFileLocation+uploadFileHupload;
                    // 自定义的文件名称
                    String trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;

                    //////////////////设置访问路径
                    //basePath拼接完成后，形如：http://192.168.1.20:8080/fileServer
                    /*String basePath0 = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
                    String fileServerPath0 = basePath0 + resourceHandler.substring(0, resourceHandler.lastIndexOf("/") + 1)  + uploadFileHupload.substring(0, uploadFileWupload.lastIndexOf("/")  + 1)+ trueFileName;
                    System.out.println("文件访问路径000：" +   fileServerPath0);*/
                    /////////////////////////////////////
                    fileServerPath = resourceHandler.substring(0, resourceHandler.lastIndexOf("/") + 1) + uploadFileHupload.substring(0, uploadFileWupload.lastIndexOf("/") + 1) + trueFileName;
                    System.out.println("文件访问路径：" + fileServerPath);


                    ////////////////////
                    // 设置存放图片文件的路径
                    path = realPath  + trueFileName;
                    logger.info("存放图片文件的路径:" + path);
                    file.transferTo(new File(path));
                    logger.info("文件成功上传到指定目录下");
                }else {
                    logger.info("不是我们想要的文件类型,请按要求重新上传");
                    result.put("url", null);
                    return result;
                }
            }else {
                logger.info("文件类型为空");
                result.put("url", null);
                return result;
            }
        }else {
            logger.info("没有找到相对应的文件");
            result.put("url", null);
            return result;
        }
        result.put("url",fileServerPath);
        return result;


    }





    /**
     *
     * 功能描述: 跳到Catehory1管理
     *
     *
     */
    @RequestMapping("/category1Manage")
    public String category1Manage() {
        logger.info("进入Category1");
        return "/category1/category1Manage";
    }

    /**
     *
     * 功能描述: 获取category1列表
     *
     */
    @RequestMapping(value = "/category1List", method = RequestMethod.GET)
    @ResponseBody
    public PageDataResult category1List(@RequestParam("pageNum") Integer pageNum,
                                         @RequestParam("pageSize") Integer pageSize){
        logger.info("获取权限菜单列表");
        PageDataResult pdr = new PageDataResult();
        try {
            if(null == pageNum) {
                pageNum = 1;
            }
            if(null == pageSize) {
                pageSize = 10;
            }
            // 获取服务类目列表
            pdr = category1Service.geCategory1List(pageNum ,pageSize);
            logger.info("category1列表查询=pdr:" + pdr);

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("category1列表查询异常！", e);
        }
        return pdr;
    }

    /**
     *
     * 功能描述: 获取角色列表
     *
     *
     */
    @GetMapping("getCategory1s")
    @ResponseBody
    public List<Category1DTO> getCategory1s(){
        logger.info("获取category1列表");
        return category1Service.getCategory1s();
    }

    /**
     *
     *述: 设置角色[新增或更新]
     *
     *
     */
    @PostMapping("setCategory1")
    @ResponseBody
    public Map<String,Object> setCategory1(Category1 category1) {
        logger.info("设置category1[新增或更新]！category1:" + category1);
        Map<String,Object> data = new HashMap();
        if(category1.getCategory1Id() == null){
            //新增角色
            data = category1Service.addCategory1(category1);
        }else{
            //修改角色
            data = category1Service.updateCategory1(category1);
        }
        return data;
    }


    /**
     *
     * 功能描述: 删除/恢复角色
     *
     */
    @PostMapping("updateCategory1Status")
    @ResponseBody
    public Map<String,Object> updateCategory1Status(@RequestParam("category1Id") int category1Id,@RequestParam("status") Integer status) {
        logger.info("删除/恢复角色！category1Id:" + category1Id+" status:"+status);
        Map<String, Object> data = new HashMap<>();
        if(status == 1){
            //删除角色
            data = category1Service.delCategory1(category1Id,status);
        }else{
            //恢复角色
            data = category1Service.recoverCategory1(category1Id,status);
        }
        return data;
    }









}
